#!/bin/bash
# hooks/post_push
# https://docs.docker.com/docker-cloud/builds/advanced/
# https://semver.org/
# https://github.com/ckulka/docker-multi-arch-example/

## requires to be a os/arch combination
DEFAULT_ARCH="linux/amd64"

## Use manifest-tool to create the manifest, given the experimental
## "docker manifest" command isn't available yet on Docker Hub.
TOOL_DOWNLOAD_URL="https://github.com/estesp/manifest-tool/releases/download"
TOOL_LATEST_TAG=$(curl -s https://api.github.com/repos/estesp/manifest-tool/tags \
    | grep 'name.*v[0-9]' \
    | head -n 1 \
    | cut -d '"' -f 4)

echo "[***] Downloading ${TOOL_DOWNLOAD_URL}/${TOOL_LATEST_TAG}/manifest-tool-linux-amd64"
curl -Lo manifest-tool ${TOOL_DOWNLOAD_URL}/${TOOL_LATEST_TAG}/manifest-tool-linux-amd64
chmod +x manifest-tool


## add_tag will add a tag and a manifest for each version
function add_tag() {
    echo "[***] Adding tag ${1}"
    docker tag $IMAGE_NAME $DOCKER_REPO:$1
    docker push $DOCKER_REPO:$1

    echo "[---] Running ./manifest-tool push from-args --platforms '${2}' --template '${IMAGE_NAME}_ARCHVARIANT' --target '${DOCKER_REPO}:${1}'"
    ./manifest-tool push from-args \
        --platforms ${2} \
        --template ${IMAGE_NAME}_ARCHVARIANT \
        --target ${DOCKER_REPO}:${1}
}


## Push all variant images
## must be done in post_push
for FILE in ${DOCKERFILE_PATH}.*
do
    TARGET_ARCH=$(echo "${FILE}" | cut -d '.' -f 2)

    echo "[---] TARGET_ARCH: ${TARGET_ARCH}"

    ## FUDGE Factor because Docker Hub does not respect "32"
    case "$TARGET_ARCH" in
        *arm32v5)
            BUILD_ARCH="armv5"
            ;;
        *arm32v6)
            BUILD_ARCH="armv6"
            ;;
        *arm32v7)
            BUILD_ARCH="armv7"
            ;;
        *)
            BUILD_ARCH="${TARGET_ARCH}"
            ;;
    esac

    echo "[---] BUILD_ARCH: ${BUILD_ARCH}"

    docker push ${IMAGE_NAME}_${BUILD_ARCH}
done

